<template>
  <div>
    <div class="page-header">
      <h2 style="margin-top: 0">评委管理与推荐</h2>
      <p class="description">管理各专业组的评委信息</p>
    </div>

    <div class="card-container">
      <!-- 专业组选项卡 -->
      <el-tabs v-model="activeTab" type="card" style="margin-bottom: 15px;" @tab-click="handleTabClick">
        <el-tab-pane label="油气勘探" name="油气勘探"></el-tab-pane>
        <el-tab-pane label="油气藏工程" name="油气藏工程"></el-tab-pane>
        <el-tab-pane label="钻采与地面工程" name="钻采与地面工程"></el-tab-pane>
        <el-tab-pane label="信息工程" name="信息工程"></el-tab-pane>
      </el-tabs>

      <!-- 操作按钮组 -->
      <div class="action-buttons">
        <el-button
            type="primary"
            icon="el-icon-random"
            @click="openRecommendDialog"
        >
          评委推荐
        </el-button>
        <el-button
            type="success"
            icon="el-icon-plus"
            @click="openExpertSelectionDialog"
        >
          手动添加
        </el-button>
        <el-button
            type="warning"
            icon="el-icon-delete"
            @click="batchDeleteJudges"
            :disabled="!hasSelectedJudges"
        >
          批量删除
        </el-button>
        <!-- 新增批量导出按钮 -->
        <el-button
            type="info"
            icon="el-icon-download"
            @click="exportCurrentGroupJudges"
            :disabled="currentTabJudges.length === 0"
        >
          批量导出
        </el-button>
      </div>

      <!-- 评委列表 -->
      <div>
        <el-table
            :data="currentTabJudges"
            border
            style="width: 100%;"
            v-loading="loading"
            element-loading-text="正在加载评委数据..."
            @selection-change="handleSelectionChange"
        >
          <el-table-column
              type="selection"
              width="55"
          ></el-table-column>
          <el-table-column
              type="index"
              label="序号"
              width="60"
              align="center"
          ></el-table-column>
          <el-table-column
              prop="expertName"
              label="评委姓名"
          ></el-table-column>
          <el-table-column
              prop="expertCategory"
              label="专家类别"
          >
            <template slot-scope="scope">
              <el-tag :type="getCategoryTagType(scope.row.expertCategory)">
                {{ scope.row.expertCategory }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column
              prop="judgeCode"
              label="登录密码"
          >
            <template slot-scope="scope">
              <span v-if="!scope.row.showPassword">******</span>
              <span v-else>{{ scope.row.judgeCode }}</span>
              <el-button
                  v-if="scope.row.showPassword && scope.row.judgeCode"
                  type="text"
                  size="mini"
                  @click="copyPassword(scope.row.judgeCode)"
                  icon="el-icon-document-copy"
              >
                复制
              </el-button>
              <el-button
                  type="text"
                  size="mini"
                  @click="togglePasswordVisibility(scope.row)"
                  :disabled="!scope.row.judgeCode"
              >
                {{ scope.row.showPassword ? '隐藏' : '显示' }}
              </el-button>
            </template>
          </el-table-column>
          <el-table-column
              prop="codeStatus"
              label="密码状态"
          >
            <template slot-scope="scope">
              <el-tag :type="scope.row.codeStatus === 1 ? 'success' : 'danger'">
                {{ scope.row.codeStatus === 1 ? '有效' : '失效' }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column
              label="操作"
              width="220"
          >
            <template slot-scope="scope">
              <el-button
                  size="mini"
                  type="text"
                  icon="el-icon-view"
                  @click="viewJudgeDetails(scope.row)"
              >
                详情
              </el-button>
              <el-button
                  size="mini"
                  type="text"
                  icon="el-icon-refresh"
                  @click="resetJudgePassword(scope.row)"
                  :disabled="!scope.row.judgeCode"
              >
                重置密码
              </el-button>
              <el-button
                  size="mini"
                  type="text"
                  icon="el-icon-delete"
                  style="color: #ff4d4f;"
                  @click="removeJudge(scope.row)"
              >
                移除
              </el-button>
            </template>
          </el-table-column>
        </el-table>

        <!-- 分页 -->
        <el-pagination
            v-if="total > 0"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
            :current-page="currentPage"
            :page-sizes="[10, 20, 50, 100]"
            :page-size="pageSize"
            layout="total, sizes, prev, pager, next, jumper"
            :total="total"
            style="margin-top: 15px; text-align: right;"
        ></el-pagination>
      </div>
    </div>

    <!-- 专家选择对话框（手动添加用） -->
    <el-dialog
        title="选择专家添加为评委"
        :visible.sync="showExpertSelectionDialog"
        width="700px"
        top="10%"
        :before-close="handleDialogClose"
    >
      <div class="dialog-content">
        <p>当前专业组：<span class="specialty-label">{{ activeTab }}</span></p>

        <!-- 搜索区域 -->
        <div class="search-container">
          <el-input
              placeholder="搜索专家姓名..."
              prefix-icon="el-icon-search"
              v-model="expertSearchKeyword"
              @input="handleSearchInput"
              clearable
          ></el-input>

          <el-select
              v-model="selectedCategory"
              placeholder="专家分类"
              clearable
              @change="handleCategoryChange"
          >
            <el-option label="全部分类" value=""></el-option>
            <el-option label="公司领导" value="公司领导"></el-option>
            <el-option label="公司副总及专家" value="公司副总及专家"></el-option>
            <el-option label="科研单位" value="科研单位"></el-option>
            <el-option label="二级单位" value="二级单位"></el-option>
            <el-option label="专业部门领导（专家）" value="专业部门领导（专家）"></el-option>
          </el-select>
        </div>

        <!-- 专家列表区域（带滚动条） -->
        <div class="experts-table-container">
          <el-table
              :data="filteredExperts"
              border
              style="width: 100%;"
              v-loading="expertLoading"
              element-loading-text="正在加载专家数据..."
              @selection-change="handleExpertSelectionChange"
          >
            <el-table-column
                type="selection"
                width="55"
            ></el-table-column>
            <el-table-column
                type="index"
                label="序号"
                width="60"
                align="center"
            ></el-table-column>
            <el-table-column
                prop="name"
                label="专家姓名"
                width="120"
            ></el-table-column>
            <el-table-column
                prop="category"
                label="专家类别"
            >
              <template slot-scope="scope">
                <el-tag :type="getCategoryTagType(scope.row.category)">
                  {{ scope.row.category }}
                </el-tag>
              </template>
            </el-table-column>
            <el-table-column
                prop="specialty"
                label="所属专业组"
            ></el-table-column>
            <el-table-column
                prop="contactInfo"
                label="联系方式"
            ></el-table-column>
          </el-table>

          <div v-if="!expertLoading && filteredExperts.length === 0" class="empty-experts">
            <el-empty description="未找到符合条件的专家"></el-empty>
          </div>

          <!-- 专家列表分页 -->
          <el-pagination
              v-if="expertTotal > 0"
              @size-change="handleExpertSizeChange"
              @current-change="handleExpertCurrentChange"
              :current-page="expertCurrentPage"
              :page-sizes="[10, 20, 50]"
              :page-size="expertPageSize"
              layout="total, sizes, prev, pager, next, jumper"
              :total="expertTotal"
              style="margin-top: 15px; text-align: right;"
          ></el-pagination>
        </div>
      </div>

      <div slot="footer">
        <el-button @click="showExpertSelectionDialog = false">取消</el-button>
        <el-button
            type="primary"
            @click="addSelectedExpertsAsJudges"
            :disabled="selectedExperts.length === 0 || isSaving"
        >
          <i v-if="isSaving" class="el-icon-loading"></i>
          添加选中的 {{ selectedExperts.length }} 位专家
        </el-button>
      </div>
    </el-dialog>

    <!-- 评委推荐对话框 -->
    <el-dialog
        title="随机推荐评委"
        :visible.sync="showRecommendDialog"
        width="800px"
        top="10%"
    >
      <el-form label-width="140px">
        <el-form-item label="当前专业组">
          <el-input
              :value="activeTab"
              disabled
          ></el-input>
        </el-form-item>
        <el-form-item label="推荐评委数量">
          <el-input v-model="judgeCount" type="number" min="1"></el-input>
        </el-form-item>

        <el-form-item label="专家类别比例设置">
          <el-row :gutter="20">
            <el-col :span="11">
              <div style="margin-bottom: 15px;">
                <div style="display: flex; justify-content: space-between; margin-bottom: 5px;">
                  <span>公司领导</span>
                  <span>{{ companyLeaderRatio }}%</span>
                </div>
                <el-slider
                    v-model="companyLeaderRatio"
                    :min="0"
                    :max="100"
                    :step="5"
                    show-input
                    @input="updateTotalRatio"
                    :disabled="isCalculating"
                ></el-slider>
              </div>

              <div style="margin-bottom: 15px;">
                <div style="display: flex; justify-content: space-between; margin-bottom: 5px;">
                  <span>公司副总及专家</span>
                  <span>{{ viceLeaderRatio }}%</span>
                </div>
                <el-slider
                    v-model="viceLeaderRatio"
                    :min="0"
                    :max="100"
                    :step="5"
                    show-input
                    @input="updateTotalRatio"
                    :disabled="isCalculating"
                ></el-slider>
              </div>

              <div style="margin-bottom: 15px;">
                <div style="display: flex; justify-content: space-between; margin-bottom: 5px;">
                  <span>专业部门领导（专家）</span>
                  <span>{{ professionalLeaderRatio }}%</span>
                </div>
                <el-slider
                    v-model="professionalLeaderRatio"
                    :min="0"
                    :max="100"
                    :step="5"
                    show-input
                    @input="updateTotalRatio"
                    :disabled="isCalculating"
                ></el-slider>
              </div>
            </el-col>

            <el-col :span="11">
              <div style="margin-bottom: 15px;">
                <div style="display: flex; justify-content: space-between; margin-bottom: 5px;">
                  <span>科研单位</span>
                  <span>{{ researchRatio }}%</span>
                </div>
                <el-slider
                    v-model="researchRatio"
                    :min="0"
                    :max="100"
                    :step="5"
                    show-input
                    @input="updateTotalRatio"
                    :disabled="isCalculating"
                ></el-slider>
              </div>

              <div style="margin-bottom: 15px;">
                <div style="display: flex; justify-content: space-between; margin-bottom: 5px;">
                  <span>二级单位</span>
                  <span>{{ secondaryUnitRatio }}%</span>
                </div>
                <el-slider
                    v-model="secondaryUnitRatio"
                    :min="0"
                    :max="100"
                    :step="5"
                    show-input
                    @input="updateTotalRatio"
                    :disabled="isCalculating"
                ></el-slider>
              </div>
            </el-col>
          </el-row>

          <div style="text-align: right; margin-top: 10px;">
            <el-tag :type="totalRatio === 100 ? 'success' : 'warning'">
              总比例: {{ totalRatio }}%
            </el-tag>
          </div>
        </el-form-item>
      </el-form>

      <div slot="footer">
        <el-button @click="showRecommendDialog = false" :disabled="isCalculating">取消</el-button>
        <el-button
            type="primary"
            @click="confirmRecommendJudges"
            :disabled="totalRatio !== 100 || !judgeCount || isCalculating"
        >
          <i v-if="isCalculating" class="el-icon-loading"></i>
          随机推荐评委
        </el-button>
      </div>
    </el-dialog>

    <!-- 其他弹窗保持不变 -->
    <!-- 评委详情弹窗 -->
    <el-dialog
        title="评委详情"
        :visible.sync="showJudgeDetailDialog"
        width="500px"
        top="15%"
    >
      <el-descriptions column="1" border>
        <el-descriptions-item label="本次分配专业组">{{ currentJudge.specialty }}</el-descriptions-item>
        <el-descriptions-item label="评委姓名">{{ currentJudge.expertName }}</el-descriptions-item>
        <el-descriptions-item label="专家类别">{{ currentJudge.expertCategory }}</el-descriptions-item>
        <el-descriptions-item label="所属专业组">{{ currentJudge.expertSpecialty }}</el-descriptions-item>
        <el-descriptions-item label="联系方式">{{ currentJudge.expertContact }}</el-descriptions-item>
        <el-descriptions-item label="登录密码">{{ currentJudge.judgeCode || '未生成' }}</el-descriptions-item>
        <el-descriptions-item label="密码状态">
          <el-tag :type="currentJudge.codeStatus === 1 ? 'success' : 'danger'">
            {{ currentJudge.codeStatus === 1 ? '有效' : '失效' }}
          </el-tag>
        </el-descriptions-item>
      </el-descriptions>
    </el-dialog>

    <!-- 移除评委确认弹窗 -->
    <el-dialog
        title="确认移除"
        :visible.sync="showRemoveConfirmDialog"
        width="300px"
        top="30%"
        :show-close="false"
    >
      <div style="text-align: center; padding: 20px 0;">
        <i class="el-icon-warning" style="color: #faad14; font-size: 24px; margin-right: 10px;"></i>
        <span>确定要移除【{{ currentJudge.expertName }}】吗？</span>
      </div>
      <div slot="footer" style="text-align: center;">
        <el-button @click="showRemoveConfirmDialog = false">取消</el-button>
        <el-button type="danger" @click="confirmRemove">确定移除</el-button>
      </div>
    </el-dialog>

    <!-- 批量删除确认弹窗 -->
    <el-dialog
        title="批量删除确认"
        :visible.sync="showBatchRemoveConfirmDialog"
        width="300px"
        top="30%"
        :show-close="false"
    >
      <div style="text-align: center; padding: 20px 0;">
        <i class="el-icon-warning" style="color: #faad14; font-size: 24px; margin-right: 10px;"></i>
        <span>确定要删除选中的 {{ selectedJudges.length }} 位评委吗？</span>
      </div>
      <div slot="footer" style="text-align: center;">
        <el-button @click="showBatchRemoveConfirmDialog = false">取消</el-button>
        <el-button type="danger" @click="confirmBatchRemove">确定删除</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {getJudgePage, saveJudge, deleteJudge, deleteJudgeBatch, recommendJudges, exportJudges} from '@/api/judge';
import {getExpertPage} from '@/api/expert'; // 导入专家分页查询接口
import {saveJudgeBatch} from '@/api/judge'; // 导入批量保存评委接口

export default {
  name: 'ReviewerRecommend',
  data() {
    return {
      // 活跃的专业组选项卡
      activeTab: '油气勘探',

      // 评委数据 - 按专业组组织
      judgeData: {
        '油气勘探': [],
        '油气藏工程': [],
        '钻采与地面工程': [],
        '信息工程': []
      },

      // 分页总条数
      total: 0,

      // 分页相关
      currentPage: 1,
      pageSize: 10,

      // 加载状态
      loading: false,

      // 选中的评委（用于批量操作）
      selectedJudges: [],

      // 弹窗状态
      showRecommendDialog: false,
      showRemoveConfirmDialog: false,
      showBatchRemoveConfirmDialog: false,
      showJudgeDetailDialog: false,
      showExpertSelectionDialog: false, // 专家选择对话框

      // 当前操作的评委
      currentJudge: {},

      // 专家选择相关
      expertSearchKeyword: '',
      selectedCategory: '',
      selectedExperts: [],
      filteredExperts: [],
      expertLoading: false,
      expertTotal: 0,
      expertCurrentPage: 1,
      expertPageSize: 10,
      isSaving: false,

      // 推荐评委对话框相关
      judgeCount: 10,
      companyLeaderRatio: 15,
      viceLeaderRatio: 25,
      professionalLeaderRatio: 20, // 专业部门领导（专家）比例
      researchRatio: 20,
      secondaryUnitRatio: 20,
      totalRatio: 100,
      isCalculating: false,
      // 新增导出相关状态
      isExporting: false
    };
  },

  computed: {
    // 当前选项卡的评委列表
    currentTabJudges() {
      return this.judgeData[this.activeTab] || [];
    },

    // 是否有选中的评委
    hasSelectedJudges() {
      return this.selectedJudges.length > 0;
    }
  },

  created() {
    // 页面加载时获取评委数据
    this.loadJudgeData();
  },

  methods: {
    // 加载评委数据 - 使用后端接口
    loadJudgeData() {
      this.loading = true;

      // 构造查询参数
      const params = {
        pageNum: this.currentPage,
        pageSize: this.pageSize,
        filters: {
          specialty: this.activeTab  // 按当前专业组筛选
        }
      };

      // 调用后端接口
      getJudgePage(params)
          .then(response => {
            if (response.code === '200' && response.data) {
              // 假设后端返回的IPage包含records和total属性
              const {records, total} = response.data;

              // 为每个评委添加showPassword属性用于控制密码显示
              const judgesWithPasswordFlag = records.map(judge => ({
                ...judge,
                showPassword: false,
                // 转换LocalDateTime格式为字符串（如果需要）
                createTime: judge.createTime ? this.formatDateTime(judge.createTime) : '',
                updateTime: judge.updateTime ? this.formatDateTime(judge.updateTime) : '',
                confirmTime: judge.confirmTime ? this.formatDateTime(judge.confirmTime) : ''
              }));

              this.judgeData[this.activeTab] = judgesWithPasswordFlag;
              this.total = total;
            } else {
              this.$message.error('获取评委数据失败: ' + (response.msg || '未知错误'));
              this.judgeData[this.activeTab] = [];
              this.total = 0;
            }
            this.loading = false;
          })
          .catch(error => {
            console.error('获取评委数据出错:', error);
            this.$message.error('获取评委数据时发生错误');
            this.loading = false;
          });
    },

    // 格式化日期时间
    formatDateTime(dateTime) {
      // 假设后端返回的是ISO格式字符串，如："2024-03-16T14:20:00"
      if (!dateTime) return '';

      // 简单格式化示例，实际项目中可使用moment.js等库
      const date = new Date(dateTime);
      return date.toLocaleString();
    },

    // 打开专家选择对话框
    openExpertSelectionDialog() {
      // 初始化专家列表相关参数
      this.expertSearchKeyword = '';
      this.selectedCategory = '';
      this.selectedExperts = [];
      this.expertCurrentPage = 1;
      this.showExpertSelectionDialog = true;

      // 加载专家数据
      this.loadExpertData();
    },

    // 加载专家数据
    loadExpertData() {
      this.expertLoading = true;

      // 构造查询参数
      const params = {
        pageNum: this.expertCurrentPage,
        pageSize: this.expertPageSize,
        filters: {
          name: this.expertSearchKeyword,
          category: this.selectedCategory,
          specialty: this.activeTab
        }
      };

      // 调用后端接口
      getExpertPage(params)
          .then(response => {
            if (response.code === '200' && response.data) {
              this.filteredExperts = response.data.records || [];
              this.expertTotal = response.data.total || 0;
            } else {
              this.$message.error('获取专家数据失败: ' + (response.msg || '未知错误'));
              this.filteredExperts = [];
              this.expertTotal = 0;
            }
            this.expertLoading = false;
          })
          .catch(error => {
            console.error('获取专家数据出错:', error);
            this.$message.error('获取专家数据时发生错误');
            this.expertLoading = false;
          });
    },

    // 处理搜索输入
    handleSearchInput() {
      // 重置页码，重新加载数据
      this.expertCurrentPage = 1;
      this.loadExpertData();
    },

    // 处理分类选择变化
    handleCategoryChange() {
      // 重置页码，重新加载数据
      this.expertCurrentPage = 1;
      this.loadExpertData();
    },

    // 处理专家分页大小变化
    handleExpertSizeChange(val) {
      this.expertPageSize = val;
      this.expertCurrentPage = 1;
      this.loadExpertData();
    },

    // 处理专家分页页码变化
    handleExpertCurrentChange(val) {
      this.expertCurrentPage = val;
      this.loadExpertData();
    },

    // 处理对话框关闭
    handleDialogClose() {
      this.showExpertSelectionDialog = false;
    },

    // 处理专家选择变化
    handleExpertSelectionChange(selection) {
      this.selectedExperts = selection;
    },

    // 将选中的专家添加为评委
    addSelectedExpertsAsJudges() {
      if (this.selectedExperts.length === 0) return;

      this.isSaving = true;

      // 过滤掉已经是评委的专家
      const existingJudgeIds = this.currentTabJudges.map(judge => judge.expertId);
      const newJudges = this.selectedExperts
          .filter(expert => !existingJudgeIds.includes(expert.id))
          .map(expert => ({
            specialty: this.activeTab,
            expertId: expert.id,
            judgeCode: this.generateRandomPassword(),
            codeStatus: 1
          }));

      if (newJudges.length > 0) {
        // 调用批量保存接口
        saveJudgeBatch(newJudges)
            .then(response => {
              if (response.code === '200') {
                this.$message.success(`成功添加 ${newJudges.length} 位评委`);
                // 关闭对话框
                this.showExpertSelectionDialog = false;
                // 重新加载评委数据
                this.loadJudgeData();
              } else {
                this.$message.error('添加评委失败: ' + (response.msg || '未知错误'));
              }
              this.isSaving = false;
            })
            .catch(error => {
              console.error('添加评委出错:', error);
              this.$message.error('添加评委时发生错误');
              this.isSaving = false;
            });
      } else {
        this.$message.warning('所选专家已全部是评委');
        this.isSaving = false;
      }
    },

    // 处理选项卡切换
    handleTabClick() {
      // 切换选项卡时重置分页和选中状态
      this.currentPage = 1;
      this.selectedJudges = [];
      // 加载新选项卡的数据
      this.loadJudgeData();
    },

    // 打开推荐评委对话框
    openRecommendDialog() {
      // 重置推荐对话框的默认值，确保总比例为100%
      this.judgeCount = 10;
      this.companyLeaderRatio = 15;
      this.viceLeaderRatio = 25;
      this.professionalLeaderRatio = 20; // 专业部门领导（专家）默认比例
      this.researchRatio = 20;
      this.secondaryUnitRatio = 20;
      this.updateTotalRatio();
      this.showRecommendDialog = true;
    },

    // 更新总比例
    updateTotalRatio() {
      this.totalRatio = this.companyLeaderRatio + this.viceLeaderRatio +
          this.professionalLeaderRatio + this.researchRatio + this.secondaryUnitRatio;
    },

    // 确认推荐评委
    confirmRecommendJudges() {
      this.isCalculating = true;

      // 构造请求参数，匹配后端JudgeRecommendDTO
      const recommendParams = {
        specialty: this.activeTab,
        totalCount: this.judgeCount,
        companyLeaderRatio: this.companyLeaderRatio,
        viceLeaderRatio: this.viceLeaderRatio,
        professionalLeaderRatio: this.professionalLeaderRatio, // 添加专业部门领导（专家）比例参数
        researchRatio: this.researchRatio,
        secondaryUnitRatio: this.secondaryUnitRatio
      };

      // 调用后端推荐接口
      recommendJudges(recommendParams)
          .then(response => {
            if (response.code === '200' && response.data) {
              // 为每个评委添加showPassword属性
              const newJudges = response.data.map(judge => ({
                ...judge,
                showPassword: false
              }));

              // 添加到当前专业组
              this.judgeData[this.activeTab] = [
                ...this.currentTabJudges,
                ...newJudges
              ];

              this.showRecommendDialog = false;
              this.$message.success(response.msg || `成功推荐 ${newJudges.length} 位评委`);

              // 重新加载评委数据，确保数据一致性
              this.loadJudgeData();
            } else {
              this.$message.error('推荐评委失败: ' + (response.msg || '未知错误'));
            }
            this.isCalculating = false;
          })
          .catch(error => {
            console.error('推荐评委出错:', error);
            this.$message.error('推荐评委时发生错误');
            this.isCalculating = false;
          });
    },

    // 批量删除评委
    batchDeleteJudges() {
      if (this.selectedJudges.length === 0) return;
      this.showBatchRemoveConfirmDialog = true;
    },

    // 确认批量删除
    confirmBatchRemove() {
      const judgeIds = this.selectedJudges.map(judge => judge.id);
      deleteJudgeBatch(judgeIds)
          .then(response => {
            if (response.code === '200') {
              this.judgeData[this.activeTab] = this.currentTabJudges.filter(
                  judge => !judgeIds.includes(judge.id)
              );
              this.selectedJudges = [];
              this.showBatchRemoveConfirmDialog = false;
              this.$message.success(`已删除选中的 ${judgeIds.length} 位评委`);
            } else {
              this.$message.error('批量删除评委失败: ' + (response.msg || '未知错误'));
            }
          })
          .catch(error => {
            console.error('批量删除评委出错:', error);
            this.$message.error('批量删除评委时发生错误');
          });
    },

    // 生成随机密码
    generateRandomPassword() {
      const chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
      let password = '';
      for (let i = 0; i < 8; i++) {
        password += chars.charAt(Math.floor(Math.random() * chars.length));
      }
      return password;
    },

    // 切换密码可见性
    togglePasswordVisibility(row) {
      row.showPassword = !row.showPassword;
    },

    // 查看评委详情
    viewJudgeDetails(row) {
      this.currentJudge = {...row};
      this.showJudgeDetailDialog = true;
    },

    // 重置评委密码
    resetJudgePassword(row) {
      this.$confirm(`确定要重置【${row.expertName}】的密码吗?`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        // 生成新密码
        const newPassword = this.generateRandomPassword();

        // 构造只包含必要字段的更新数据
        const updatedJudge = {
          id: row.id,
          judgeCode: newPassword,
          codeStatus: 1
        };
        // 调用API更新密码
        saveJudge(updatedJudge)
            .then(response => {
              if (response.code === '200') {
                // 更新成功后更新本地数据
                const index = this.currentTabJudges.findIndex(item => item.id === row.id);
                if (index !== -1) {
                  this.currentTabJudges[index].judgeCode = newPassword;
                  this.currentTabJudges[index].codeStatus = 1;
                }
                this.$message.success('密码已重置并保存');
              } else {
                this.$message.error('重置密码失败: ' + (response.msg || '未知错误'));
              }
            })
            .catch(error => {
              console.error('重置密码出错:', error);
              this.$message.error('重置密码时发生错误');
            });
      }).catch(() => {
        // 取消操作
      });
    },

    // 移除评委
    removeJudge(row) {
      this.currentJudge = {...row};
      this.showRemoveConfirmDialog = true;
    },

    // 确认移除评委
    confirmRemove() {
      const judgeId = this.currentJudge.id;
      deleteJudge(judgeId)
          .then(response => {
            if (response.code === '200') {
              // 成功删除后更新本地数据
              this.judgeData[this.activeTab] = this.currentTabJudges.filter(
                  judge => judge.id !== judgeId
              );
              this.showRemoveConfirmDialog = false;
              this.$message.success(`已移除评委【${this.currentJudge.expertName}】`);
            } else {
              this.$message.error('删除评委失败: ' + (response.msg || '未知错误'));
            }
          })
          .catch(error => {
            console.error('删除评委出错:', error);
            this.$message.error('删除评委时发生错误');
          });
    },

    // 处理表格选择变化
    handleSelectionChange(selection) {
      this.selectedJudges = selection;
    },

    // 分页相关方法
    handleSizeChange(val) {
      this.pageSize = val;
      this.currentPage = 1;
      this.loadJudgeData(); // 重新加载数据
    },
    handleCurrentChange(val) {
      this.currentPage = val;
      this.loadJudgeData(); // 重新加载数据
    },

    // 获取专家类别标签类型
    getCategoryTagType(category) {
      const typeMap = {
        '公司领导': 'danger',
        '公司副总及专家': 'primary',
        '专业部门领导（专家）': 'success',
        '科研单位': 'info',
        '二级单位': 'warning'
      };
      return typeMap[category] || 'info';
    },

    // 复制密码到剪贴板
    copyPassword(password) {
      if (!password) {
        this.$message.warning('密码为空，无法复制');
        return;
      }

      // 使用现代浏览器的Clipboard API
      if (navigator.clipboard && window.isSecureContext) {
        navigator.clipboard.writeText(password).then(() => {
          this.$message.success('密码已复制到剪贴板');
        }).catch(err => {
          console.error('复制失败:', err);
          this.$message.error('复制失败');
          this.fallbackCopyTextToClipboard(password);
        });
      } else {
        // 兼容性处理
        this.fallbackCopyTextToClipboard(password);
      }
    },

    // 兼容性复制方法
    fallbackCopyTextToClipboard(text) {
      const textArea = document.createElement("textarea");
      textArea.value = text;
      textArea.style.position = "fixed";
      textArea.style.left = "-999999px";
      textArea.style.top = "-999999px";
      document.body.appendChild(textArea);
      textArea.focus();
      textArea.select();

      try {
        const successful = document.execCommand('copy');
        if (successful) {
          this.$message.success('密码已复制到剪贴板');
        } else {
          this.$message.error('复制失败');
        }
      } catch (err) {
        console.error('复制操作不支持:', err);
        this.$message.error('浏览器不支持复制操作');
      }

      document.body.removeChild(textArea);
    },

    // 新增：批量导出当前组评委信息
    exportCurrentGroupJudges() {
      // 检查是否有数据可导出
      if (this.currentTabJudges.length === 0) {
        this.$message.warning('当前专业组没有评委数据可导出');
        return;
      }

      // 显示导出状态
      this.isExporting = true;
      this.$message.info('正在导出评委信息，请稍候...');

      // 调用导出API
      exportJudges(this.activeTab)
          .then(response => {
            this.isExporting = false;

            // 检查响应是否为Blob类型（直接判断最外层响应）
            if (response instanceof Blob) {
              try {
                // 1. 尝试从响应头获取文件名（兼容不同来源的响应头）
                let fileName = `评委信息_${this.activeTab || '全部'}.xlsx`;

                // 如果存在response.headers，尝试解析文件名
                if (response.headers) {
                  const contentDisposition = response.headers['content-disposition'] ||
                      response.headers['Content-Disposition'];

                  if (contentDisposition) {
                    const matches = /filename=([^;]+)/i.exec(contentDisposition);
                    if (matches && matches[1]) {
                      fileName = decodeURIComponent(matches[1].replace(/["']/g, ''));
                    }
                  }
                }

                // 2. 验证文件大小
                if (response.size === 0) {
                  this.$message.error('导出失败: 服务器返回空文件');
                  return;
                }

                // 3. 创建下载链接
                const url = window.URL.createObjectURL(response);
                const a = document.createElement('a');
                a.href = url;
                a.download = fileName;
                document.body.appendChild(a);
                a.click();

                // 4. 清理资源
                setTimeout(() => {
                  window.URL.revokeObjectURL(url);
                  document.body.removeChild(a);
                }, 100);

                this.$message.success('评委信息导出成功');
              } catch (error) {
                console.error('导出过程发生错误:', error);
                this.$message.error('导出失败: 处理文件时发生错误');
              }
            }
            // 处理可能的JSON错误响应
            else if (typeof response === 'object') {
              console.error('导出接口返回错误信息:', response);
              const errorMsg = response.msg || response.message || '服务器返回错误信息';
              this.$message.error(`导出失败: ${errorMsg}`);
            }
            // 处理其他异常情况
            else {
              console.error('导出响应格式异常:', response);
              this.$message.error('导出失败: 服务器返回格式异常');
            }
          })
          .catch(error => {
            this.isExporting = false;
            console.error('导出请求失败:', error);

            // 详细错误信息处理
            let errorMsg = '导出失败: 网络请求异常';
            if (error.message) {
              errorMsg = `导出失败: ${error.message}`;
            } else if (error.response && error.response.status) {
              errorMsg = `导出失败: HTTP状态码 ${error.response.status}`;
            }

            this.$message.error(errorMsg);
          });
    }
  }
};
</script>

<style scoped>

.specialty-tabs {
  margin-bottom: 15px;
}

.action-buttons {
  display: flex;
  gap: 10px;
  margin-bottom: 15px;
  flex-wrap: wrap;
}

/* 专家选择对话框样式 */
.dialog-content {
  padding: 10px 0;
}

.specialty-label {
  color: #1890ff;
  font-weight: bold;
  margin-bottom: 15px;
  display: inline-block;
}

/* 搜索区域样式 */
.search-container {
  display: flex;
  gap: 10px;
  margin-bottom: 15px;
  align-items: center;
}

.search-container .el-input {
  flex: 1;
}

.search-container .el-select {
  width: 200px;
}

/* 专家表格容器样式 - 带滚动条 */
.experts-table-container {
//max-height: calc(70vh); /* 调整为视口高度的70%，预留足够空间给对话框其他元素 */ //overflow-y: auto; //padding-right: 5px;
}

.empty-experts {
  padding: 40px 0;
  text-align: center;
}

/* 批量导入按钮样式调整 */
::v-deep .action-buttons .el-upload {
  display: inline-block;
}

/* 确保对话框在屏幕中间 */
/*::v-deep .el-dialog {
  transform: translateY(-50%) !important;
}*/

/* 新增专业部门领导（专家）标签样式 */
::v-deep .el-tag--purple {
  background-color: #722ed1;
  border-color: #722ed1;
  color: #fff;
}
</style>
